//
//  ViewController.swift
//  RLVideo
//
//  Created by raniys on 2018/10/10.
//  Copyright © 2018 raniys. All rights reserved.
//

import UIKit
import AVKit
import AVFoundation
import PKHUD

class ViewController: UIViewController {
    
    
    let numberOfFeedPhotosMax: Int = 300
    // maximum duration for video choose
    let maximumVideoChooseDuration: TimeInterval = 10 * 60
    // minimum clip duration for video
    let minimumVideoClipDuration: TimeInterval = 1
    
    let videoPicker = HXPhotoManager(type: .photoAndVideo)
    
    var beforeVideoModel: HXPhotoModel?
    var isVideoEditOutside: Bool = true
    var toolManager = HXDatePhotoToolManager()
    
    
    @IBOutlet weak var containerView: UIView!
    
    @IBAction func onPlayTapped(_ sender: UIButton) {
        
        guard
            let url = URL(string: "file:///Users/raniys/Library/Developer/CoreSimulator/Devices/FCB1545E-7097-4F34-B308-F0954B406E3F/data/Media/DCIM/100APPLE/IMG_0146.MOV") else { return }
        let controller = VideoPlayerController()
        controller.videoUrl = url
        self.present(controller, animated: true, completion: nil)
        
//        configureImagePicker()
//        hx_presentAlbumListViewController(with: videoPicker, delegate: self)
    }
    
    @IBAction func onImageChoose(_ sender: UITapGestureRecognizer) {

    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }
    
    
    func configureImagePicker() {
        
        videoPicker?.configuration.selectTogether = false
        videoPicker?.configuration.specialModeNeedHideVideoSelectBtn = true
        videoPicker?.configuration.videoCanEdit = true
        videoPicker?.configuration.videoMaxDuration = maximumVideoChooseDuration
        videoPicker?.configuration.openCamera = false
        videoPicker?.configuration.photoCanEdit = false
        videoPicker?.configuration.replaceVideoEditViewController = true
        videoPicker?.configuration.photoMaxNum = numberOfFeedPhotosMax
        videoPicker?.configuration.themeColor = UIColor(hex: 0x45C53E)
        
        videoPicker?.configuration.useVideoEditComplete = {(beforeMode, afterMode) in
            
        }
        videoPicker?.configuration.shouldUseEditAsset = {[unowned self](controller, isOutside, manager, beforeModel) in
            self.isVideoEditOutside = isOutside
            guard let model = beforeModel, let controller = controller else { return }
            
            if model.type == HXPhotoModelMediaTypeCameraVideo {
                
                self.gotoEditVideoController(model.videoURL, videoEdit: model.tempAsset as? LFVideoEdit, placeholderImage: model.tempImage, baseViewController: controller)
                
            } else {
                HUD.show(.labeledProgress(title: nil, subtitle: "加载中..."))
                HXPhotoTools.getAVAsset(with: model.asset, startRequestIcloud: { (requestId) in
                    
                }, progressHandler: { (progress) in
                    
                }, completion: { (avAsset) in
                    HUD.hide()
                    
                    if avAsset is AVURLAsset, let urlAsset = avAsset as? AVURLAsset {
                        
                        self.gotoEditVideoController(urlAsset.url, videoEdit: model.tempAsset as? LFVideoEdit, placeholderImage: HXPhotoTools.thumbnailImage(forVideo: urlAsset.url, atTime: 0.1), baseViewController: controller)
                        
                    } else {
                        
                        self.toolManager.writeSelectModelListToTempPath(withList: [model], success: { (allUrls, photoUrls, videoUrls) in
                            HUD.hide()
                            
                            self.gotoEditVideoController(videoUrls?.first, videoEdit: model.tempAsset as? LFVideoEdit, placeholderImage: HXPhotoTools.thumbnailImage(forVideo: videoUrls?.first, atTime: 0.1), baseViewController: controller)
                            
                        }, failed: {
                            HUD.hide()
                            HUD.flash(.labeledError(title: "加载失败", subtitle: "资源获取失败!"))
                        })
                    }
                    
                }, failed: { (errorInfo) in
                    HUD.hide()
                    HUD.flash(.labeledError(title: "加载失败", subtitle: "资源获取失败!"))
                })
                
            }
        }
        
    }
    
    func gotoEditVideoController(_ videoUrl: URL? = nil, videoEdit: LFVideoEdit? = nil, placeholderImage: UIImage, baseViewController: UIViewController) {
        guard videoUrl != nil || videoEdit != nil  else {  return }
        
        let editVideoController = LFVideoEditingController()
        editVideoController.delegate = self
        editVideoController.minClippingDuration = self.minimumVideoClipDuration
        
        if videoEdit != nil {
            editVideoController.videoEdit = videoEdit
        } else {
            editVideoController.setVideoURL(videoUrl, placeholderImage: HXPhotoTools.thumbnailImage(forVideo: videoUrl, atTime: 0.1))
        }
        
        if !self.isVideoEditOutside {
            baseViewController.navigationController?.pushViewController(editVideoController, animated: false)
        } else {
            let navController = HXCustomNavigationController(rootViewController: editVideoController)
            navController.supportRotation = false
            baseViewController.present(navController, animated: false, completion: nil)
        }
    }
    
    
    /// load photo by asset and size from system photo library
    ///
    /// - Parameters:
    ///   - asset: photo asset
    ///   - size: target size
    ///   - completion: handler called when photo loaded
    open func loadImage(with asset: PHAsset, target size: CGSize? = nil, completion: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) {
        
        var targetSize = PHImageManagerMaximumSize
        if let size = size {
            targetSize = CGSize(width: size.width * UIScreen.main.scale, height: size.height * UIScreen.main.scale)
        }
        
        let option = PHImageRequestOptions()
        option.isNetworkAccessAllowed = true
        option.isSynchronous = true
        option.deliveryMode = .highQualityFormat
        
        PHImageManager.default().requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFill, options: option) { (image, info) in
            completion(image, info)
        }
        
    }
}


extension ViewController: HXAlbumListViewControllerDelegate {
    func albumListViewController(_ albumListViewController: HXAlbumListViewController!, didDoneAllList allList: [HXPhotoModel]!, photos photoList: [HXPhotoModel]!, videos videoList: [HXPhotoModel]!, original: Bool) {
        
        guard
            let url = URL(string: "file:///Users/raniys/Library/Developer/CoreSimulator/Devices/FCB1545E-7097-4F34-B308-F0954B406E3F/data/Media/DCIM/100APPLE/IMG_0146.MOV") else { return }
        let controller = VideoPlayerController()
        controller.videoUrl = url
        
        delay(1) {
            self.navigationController?.present(controller, animated: true, completion: nil)
        }
        
    }
}


// MARK: - LFVideoEditingControllerDelegate

extension ViewController: LFVideoEditingControllerDelegate {
    
    func lf_VideoEditingController(_ videoEditingVC: LFVideoEditingController!, didCancelPhotoEdit videoEdit: LFVideoEdit!) {
        
        if videoEditingVC.navigationController?.viewControllers.count ?? 0 > 1 {
            videoEditingVC.navigationController?.popViewController(animated: false)
        } else {
            videoEditingVC.dismiss(animated: false, completion: nil)
        }
        
    }
    
    func lf_VideoEditingController(_ videoEditingVC: LFVideoEditingController!, didFinishPhotoEdit videoEdit: LFVideoEdit!) {
        
        guard let url = videoEdit.editFinalURL else { return }
        
        let controller = UIStoryboard(name: "Video", bundle: nil).instantiateViewController(withIdentifier: "VideoCropController") as! VideoCropController
        controller.videoUrl = url
        
        let shadowImage = videoEditingVC.navigationController?.navigationBar.shadowImage
        let backgroundImage = videoEditingVC.navigationController?.navigationBar.backgroundImage(for: .default)
        let tintColor = videoEditingVC.navigationController?.navigationBar.tintColor
        let titleTextAttributes = videoEditingVC.navigationController?.navigationBar.titleTextAttributes
        controller.completionHandler = {(image, name) in
            videoEditingVC.navigationController?.navigationBar.shadowImage = shadowImage
            videoEditingVC.navigationController?.navigationBar.setBackgroundImage(backgroundImage, for: .default)
            videoEditingVC.navigationController?.navigationBar.tintColor = tintColor
            videoEditingVC.navigationController?.navigationBar.titleTextAttributes = titleTextAttributes
            if let image = image {
                if videoEditingVC.navigationController?.viewControllers.count ?? 0 > 1 {
                    videoEditingVC.navigationController?.popViewController(animated: false)
                } else {
                    videoEditingVC.dismiss(animated: false, completion: nil)
                }
                
                let model = HXPhotoModel(videoURL: url)
                model?.tempAsset = videoEdit
                model?.videoCoverPhoto = image
                self.videoPicker?.configuration.useVideoEditComplete(self.beforeVideoModel, model)
            }
        }
        
        videoEditingVC.navigationController?.navigationBar.shadowImage = UIImage()
        videoEditingVC.navigationController?.navigationBar.setBackgroundImage(UIImage(color: UIColor.clear), for: .default)
        videoEditingVC.navigationController?.navigationBar.tintColor = UIColor.white
        videoEditingVC.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
        videoEditingVC.navigationController?.pushViewController(controller, animated: true)
    }
}
